from playwright.sync_api import sync_playwright, BrowserContext
from .page import BrowserPage
import os

user_profile = os.path.expandvars('%USERPROFILE%')
crawler_dir = os.path.join(user_profile, '.cranythings')

class Browser:
    def __init__(self, headless=True):
        self.playwright = sync_playwright().start()
        self.context: BrowserContext
        self._init_context(headless)
        pass

    def _init_context(self, headless: bool):
        self.context = self.playwright.chromium.launch_persistent_context(
            user_data_dir=crawler_dir,
            headless=headless,
            # 关键设置：隐藏自动化特征
            bypass_csp=True,  # 绕过内容安全策略（某些检测脚本依赖 CSP）
            java_script_enabled=True,
            args=["--start-maximized"]
        )
        pass

    def set_headless(self, headless: bool):
        self.context.close()
        self._init_context(headless)
        pass

    def open(self, url='', wait_for_network_idle=False):
        page = BrowserPage(self.context.new_page(), self.context)
        if url:
            page.navigate_to(url)
            if wait_for_network_idle:
                page.page_context.wait_for_load_state('networkidle')
                pass
            pass
        return page

    def close(self):
        self.context.close()
        self.playwright.stop()
        pass

    pass
